<?php

namespace Beerus\Modules\DecoCompany\Actions;

use Doraemon\cache\Queue;
use Doraemon\service\DecoCompanyEvaluationService;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Doraemon\model\DecoCompanyEvaluation;


class RecoverEvaluate extends RowAction
{
    public $name = '恢复评价';
    const TOAST_ALERT = '确认将该条评价恢复嘛?恢复后将把该条评价展示!';

    public function handle($id)
    {
        $eva_info = DecoCompanyEvaluation::get('*', [
            'id' => $id,
        ]);

        // 5.23 判断该用户对该装企是否已经有一条正常的sign_status评价,如果有不允许恢复;
        $single_evaluation_num = DecoCompanyEvaluation::getEvaluationSignNum($eva_info['from_uid'], $eva_info['to_uid'], $eva_info['sign_status']);
        if ((int)$single_evaluation_num === DecoCompanyEvaluationService::MAX_SINGLE_EVALUATION_NUM) {
            return $this->response()->error('该用户已经评价过啦,无法再恢复评价啦o(TωT)o');
        }

        $update_data['data_status'] = DecoCompanyEvaluation::STATUS_NORMAL;
        $evaluate_result = DecoCompanyEvaluation::updateInfo($id,$update_data);
        if ($evaluate_result){
            if ($eva_info['type'] == DecoCompanyEvaluation::TYPE_USER_EVALUATION) {
                DecoCompanyEvaluationService::reCalculateScore($eva_info['to_uid']);

                // 同步评价好评率
                Queue::insertQueue('/queue/Decocompany/AsyncFavorRating',[
                    'uid' => $eva_info['to_uid'],
                ], Queue::QUEUE_DORAEMON);
            }
            return $this->response()->success('恢复该评价成功(*^__^*)')->refresh();
        }else{
            return $this->response()->error('恢复该评价失败,请稍后重试o(TωT)o');
        }

    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function dialog()
    {
        $this->confirm(self::TOAST_ALERT);
    }
}
